class window.Texture
  constructor : (@ctx, @type, @imageFormat, @formatType, @internalFormat) ->
    @gl = @ctx.gl
    
    @internalFormat ?= @gl.RGBA
    @imageFormat ?= @gl.RGBA
    @formatType ?= @gl.UNSIGNED_BYTE

    @type ?= @gl.TEXTURE_2D

    @texture = @gl.createTexture()
    @filterNearest()
    @width = 0
    @height = 0
    @ready = false



  getSampler : -> @texture
  bind : ->
    @gl.bindTexture @type, @texture

  setImageData : (imgDefer) ->
    @ready = false
    _defer = new window.mq.Defer()
    @loader = _defer

    me = @
    imgDefer.then (img) ->
      me.ready = true
      me.width = img.width
      me.height = img.height
      me.bind()
      me.gl.texImage2D me.type, 0, me.internalFormat, me.imageFormat, me.formatType, img
      _defer.resolve true

    return _defer
  
  load : (src) ->
    @setImageData window.loadImage(src)

  filterNearest : ->
    @bind()
    @gl.texParameteri @type, @gl.TEXTURE_MAG_FILTER, @gl.NEAREST
    @gl.texParameteri @type, @gl.TEXTURE_MIN_FILTER, @gl.NEAREST


  filterLinear : ->
    @bind()
    @gl.texParameteri @type, @gl.TEXTURE_MAG_FILTER, @gl.LINEAR
    @gl.texParameteri @type, @gl.TEXTURE_MIN_FILTER, @gl.LINEAR